package com.estate.web.controller.report.report;

import com.estate.common.core.domain.AjaxResult;
import com.estate.common.core.domain.BaseEntity;
import com.estate.common.utils.DateUtils;
import com.estate.report.domain.dto.PerformanceStatisticsDto;
import com.estate.report.domain.vo.SummaryStatisticsVo;
import com.estate.report.domain.vo.TrendStatisticsVo;
import com.estate.report.enums.StatisticsSearchTypeEnum;
import com.estate.report.service.IDataStatisticsService;
import com.estate.system.domain.report.saledepartmentmanager.departmentanalysis.DealsClosed;
import com.estate.system.domain.report.saledepartmentmanager.departmentanalysis.MidPriceOfSale;
import com.estate.system.domain.report.saledepartmentmanager.departmentanalysis.NewLeads;
import com.estate.system.domain.report.saledepartmentmanager.departmentanalysis.TotalSaleGmv;
import com.estate.system.domain.vo.ComparisonAnalysisGenerator;
import com.estate.system.domain.vo.GmvTrendDataGenerator;
import com.estate.system.service.ISysUserService;
import com.estate.system.service.impl.DataListingsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.estate.web.controller.report.report.BossController.parseFindings;

@RestController
@RequestMapping("/report/pmDepartmentManage")
public class PmDepartmentManagerController {

    @Autowired
    private ISysUserService userService;
    @Resource
    private DataListingsServiceImpl dataListingsService;
    @Resource
    private IDataStatisticsService dataStatisticsService;

    /**
     * 获取近七天新增客户咨询数量
     *
     * @param paramData key1:xDays 表示要查询最近x天的数据
     * @return sevenDaysAgoCount：最近7天数量  fourteenDaysAgoCount：上一个7天的数量 addPercentage:最近7天新增百分比
     */
//    @PreAuthorize("@ss.hasPermi('sale:getSevenDayNewEnquire')")
    @GetMapping("/getKeyFindings")
    public AjaxResult getKeyFindings(Map<String, Object> paramData) {
        ZoneId australiaSydney = ZoneId.of("Australia/Sydney");
        ZonedDateTime now = ZonedDateTime.now(australiaSydney);
        // 设置日期时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String queryDate = now.format(formatter);
        String keyFinding = dataListingsService.getKeyFindings(queryDate,"lease");
        List<String> findings =parseFindings(keyFinding);
        return AjaxResult.success("success", findings);
    }

    @GetMapping("/getDepartmentAnalysis")
    public AjaxResult getMarketGrowthPotential(Map<String, Object> paramData) {
        Map<String, Object> result = new HashMap<>();

        SummaryStatisticsVo gmvData = (SummaryStatisticsVo) dataStatisticsService.getStatisticsData(StatisticsSearchTypeEnum.LEASE_GMV.getType());
        result.put("TotalSalesGMV", new TotalSaleGmv(gmvData.getData(),gmvData.getComparableRate()));


        SummaryStatisticsVo dealsClosedData =
                (SummaryStatisticsVo) dataStatisticsService.getStatisticsData(StatisticsSearchTypeEnum.LEASE_NUM.getType());
        result.put("DealsClosed", new DealsClosed(dealsClosedData.getData(),dealsClosedData.getComparableRate()));


        SummaryStatisticsVo newLeadsData =
                (SummaryStatisticsVo) dataStatisticsService.getStatisticsData(StatisticsSearchTypeEnum.LEASE_NEW_LEADS.getType());
        result.put("NewLeads", new NewLeads(newLeadsData.getData(),newLeadsData.getComparableRate()));


        SummaryStatisticsVo midPriceData = (SummaryStatisticsVo) dataStatisticsService.getStatisticsData(StatisticsSearchTypeEnum.LEASE_MID_PRICE.getType());
        result.put("MidPriceOfSale", new MidPriceOfSale(midPriceData.getData(),midPriceData.getComparableRate()));

        Date weekStart = DateUtils.getWeekStart();
        Date weekEnd = DateUtils.getWeekEnd();
        List<BigDecimal> thisWeekTrendList = dataStatisticsService.getTrendList(new BaseEntity(), StatisticsSearchTypeEnum.LEASE_GMV_TREND, weekStart, weekEnd)
                .stream().map(TrendStatisticsVo::getData).collect(Collectors.toList());
        List<BigDecimal> lastWeekTrendList = dataStatisticsService.getTrendList(new BaseEntity(), StatisticsSearchTypeEnum.LEASE_GMV_TREND,
                        DateUtils.addDays(weekStart, -7), DateUtils.addDays(weekEnd, -7))
                .stream().map(TrendStatisticsVo::getData).collect(Collectors.toList());
        result.put("TrendOfGMV",GmvTrendDataGenerator.createGmvTrendData(thisWeekTrendList, lastWeekTrendList));
        return AjaxResult.success("success", result);
    }

    @GetMapping("/getSalePerformance")
    public AjaxResult getSalePerformance(Map<String, Object> paramData) {
        Map<String, Object> result = new HashMap<>();
        //Popular Suburbs Distribution
        Date weekStart = DateUtils.getWeekStart();
        Date weekEnd = DateUtils.getWeekEnd();
        result.put(
                "SalesPerformanceRank",
                dataStatisticsService.getPerformanceList(
                        new BaseEntity(),
                        PerformanceStatisticsDto.builder()
                                .priceType(StatisticsSearchTypeEnum.LEASE_GMV.getStatisticsType())
                                .numType(StatisticsSearchTypeEnum.LEASE_NUM.getStatisticsType())
                                .startTime(weekStart)
                                .endTime(weekEnd)
                                .build()
                )
        );
//        result.put("SalesInfo",new SalesInfo("James Wilson", "Sydney CBD Properties", "Michael Brown", "+14.2%", "+16.8%", "/avatars/james_w.jpg"));
        return AjaxResult.success("success", result);
    }

    @GetMapping("/getPerformanceDetail/{userId}")
    public AjaxResult getPerformanceDetail(@PathVariable("userId") Long userId) {
        userService.checkUserDataScope(userId);
        return AjaxResult.success(
                dataStatisticsService.getPerformanceDetail(
                        new BaseEntity(),
                        PerformanceStatisticsDto.builder()
                                .userId(userId)
                                .priceType(StatisticsSearchTypeEnum.LEASE_GMV.getStatisticsType())
                                .numType(StatisticsSearchTypeEnum.LEASE_NUM.getStatisticsType())
                                .startTime(DateUtils.getWeekStart())
                                .endTime(DateUtils.getWeekEnd())
                                .build()
                )
        );
    }


    @GetMapping("/getListingAnalysis")
    public AjaxResult getListingAnalysis(Map<String, Object> paramData) {
        Map<String, Object> result = new HashMap<>();
        result.put("TypeOfPropertySold", dataListingsService.generatePropertyTypeData(paramData));
        result.put("PriceIntervalOfPropertySold", dataListingsService.generateTransactionTypeData(paramData));
        result.put("SuburbOfPropertySold", dataListingsService.generatePriceRangeData(paramData));
        result.put("ComparisonAnalysis", ComparisonAnalysisGenerator.generateDataMap());
        return AjaxResult.success("success", result);
    }
}
